package org.git.movie.videojiexi;


import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.UnknownHostException;

@Controller
@RequestMapping("/video")
public class VideoJiexiController {
    public final static Logger logger = LoggerFactory.getLogger(VideoJiexiController.class);


//    @Autowired
//    private IndexController indexController;
//
//    @Autowired
//    @Qualifier("KuaiShouServiceImpl")
//    private VideoService kuaiShouService;
//
//    @Autowired
//    @Qualifier("DouyinServiceImpl")
//    private VideoService douyinServiceImpl;
//
//    @Autowired
//    @Qualifier("TencentQqServiceImpl")
//    private VideoService tencentQqServiceImpl;
//
//    @Autowired
//    @Qualifier("TencentQqServiceV2Impl")
//    private VideoService tencentQqServiceV2Impl;
//
//    @Autowired
//    @Qualifier("SougouServiceImpl")
//    private VideoService sougouService;
//
//    @Autowired
//    @Qualifier("WeishiServiceImpl")
//    private VideoService  weishiServiceImpl;
//
//
//    @RequestMapping(value = "download",method = {RequestMethod.GET})
//    public void downloadDouyin(HttpServletRequest request, HttpServletResponse response, @RequestHeader("User-Agent") String userAgent) throws Exception {
//
//
////        QrcodeUserDto userDto = UserThread.getUserSession();
////        if(userDto == null){
////            //跳转大登录页面
////            indexController.login(request,response);
////            return;
////        }
//
//
//        String url = request.getParameter("url");
//        String errorMsg = "";
//
//        VelocityContext velocityContext = new VelocityContext();
//        indexController.commenRender(request,velocityContext);
//
//        String viewName = "video/download.vm";
//        velocityContext.put("url", url);
//        velocityContext.put("errorMsg", errorMsg);
//
//        QrcodeNav qrcodeNav = new QrcodeNav();
//        qrcodeNav.setId(-2);
//        velocityContext.put("qrcodeNav",qrcodeNav);
//
//        ViewVelocity.view(request,response,viewName,velocityContext);
//
//    }
//
//    @RequestMapping(value = "download",method = {RequestMethod.POST})
//    @ResponseBody
//    public void downloadDouyin_post(HttpServletRequest request, HttpServletResponse response, @RequestHeader("User-Agent") String userAgent) throws Exception {
//
//        Map<String,Object> rep = new HashMap<>();
//
//        QrcodeUserDto userDto = UserThread.getUserSession();
//        if(userDto == null){
//            rep.put("code","-1");
//            rep.put("msg","请先登录");
//            response.getWriter().write("请先登录");
//            return ;
//        }
//        String url = request.getParameter("url");
//        if(url != null){
//            url = url.trim();
//        }
//
//        VideoModel videoModel = null;
//        if(StringUtils.isNotEmpty(url)){
//
//                try{
//                    if (url.indexOf("douyin.com") != -1 || url.indexOf("iesdouyin.com") != -1 ){
//                        if(!url.endsWith("/")){
//                            url = url+"/";
//                        }
//                       videoModel =   douyinServiceImpl.parseUrl(url,userAgent);
//                        beforRender(  response,  videoModel,  null);
////                        beforRender4Douyin(  response,  videoModel,  userAgent,url);
//
//                    }else   if(url.indexOf("chenzhongtech.com")>=0){
//                        videoModel =  kuaiShouService.parseUrl(url,userAgent);
//                        beforRender(  response,  videoModel,  userAgent);
//
//                    }else   if(url.indexOf("v.qq.com")>=0){
//                        videoModel =  tencentQqServiceImpl.parseUrl(url,userAgent);
//                        beforRender(  response,  videoModel,  userAgent);
//                    }else   if(url.indexOf("qb://video/feedsvideo/list")>=0 || url.indexOf("https://v.html5.qq.com/node/h5videoPlayer")>=0){
//                        videoModel =  tencentQqServiceV2Impl.parseUrl(url,userAgent);
//                        beforRender(  response,  videoModel,  userAgent);
//                    }else   if(url.indexOf("wapv.sogou.com")>=0){
//                        videoModel =  sougouService.parseUrl(url,userAgent);
//                        beforRender(  response,  videoModel,  userAgent);
//                    }else   if(url.indexOf("h5.weishi.qq.com")>=0){
//                        videoModel =  weishiServiceImpl.parseUrl(url,userAgent);
//                        beforRender(  response,  videoModel,  userAgent);
//                    }
//
//                }catch (Exception e){
//                    logger.error("下载视频失败，url="+url,e);
//
//
//                }
//
//        }
//        if(videoModel == null){
//            rep.put("code","1");
//
//            rep.put("msg","解析失败");
//        }else {
//            rep.put("code","0");
//            rep.put("msg","解析成功");
//            rep.put("data",videoModel);
//        }
//        logger.info("正常返回，url="+url);
//
////        return rep;
//
//
//
//
//    }
//
//    public void beforRender(HttpServletResponse response,VideoModel videoModel,String userAgent) throws IOException {
//        if(videoModel == null){
//            return;
//        }else {
//            BufferedInputStream inStream = null;
//            if(videoModel.getChannel().equals(VideoChannel.DOUYIN)){
//                Map<String, String> headers = new HashMap<>();
//                headers.put("Connection", "keep-alive");
//                headers.put("Host", "aweme.snssdk.com");
//                if(userAgent == null){
//                    userAgent = "Mozilla/5.0 (iPhone; CPU iPhone OS 12_1_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/16D57 Version/12.0 Safari/604.1";
//
//                }
//                headers.put("User-Agent",userAgent);
//
//
//                //6.利用Joup获取视频对象,并作封装成一个输入流对象
//                  inStream = Jsoup.connect(videoModel.getPlayAddr()).headers(headers).timeout(10000).ignoreContentType(true).execute().bodyStream();
//            }else {
//                inStream = Jsoup.connect(videoModel.getPlayAddr()).timeout(10000).ignoreContentType(true).execute().bodyStream();
//            }
//
//            Date now = new Date();
//
//            String   filename = now.getTime()+".mp4";
//
//            response.reset();
//            //设置response
//            response.setContentType("video/mpeg4");
//            response.setHeader("content-disposition", "attachment; filename="+VideoHelper.buidFileName(userAgent,filename));
//
//            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
//            int i = -1;
//            while ((i = inStream.read()) != -1) {
//                toClient.write(i);
//            }
//            inStream.close();
//
////        OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
////        toClient.write(buffer);
//            toClient.flush();
//            toClient.close();
//
//        }
//
//    }

//    public static void loadVideo(String url,HttpServletResponse response,String userAgent) throws IOException {
//
//        //过滤链接，获取http连接地址
//        String finalUrl = VideoHelper.decodeHttpUrl(url);
//
//        //1.利用Jsoup抓取抖音链接
//        //抓取抖音网页
//        String htmls = Jsoup.connect(finalUrl).ignoreContentType(true).execute().body();
//        //System.out.println(htmls); //做测试时使用
//
//        //2.利用正则匹配可以抖音下载链接
//        //playAddr: "https://aweme.snssdk.com/aweme/v1/playwm/?video_id=v0200ffc0000bfil6o4mavffbmroeo80&line=0",
//        //具体匹配内容格式：「https://aweme.snssdk.com/aweme/...line=0」
//        Pattern patternCompile = Pattern.compile("(?<=playAddr: \")https?://.+(?=\",)");
//        //利用Pattern.compile("正则条件").matcher("匹配的字符串对象")方法可以将需要匹配的字段进行匹配封装 返回一个封装了匹配的字符串Matcher对象
//
//        //3.匹配后封装成Matcher对象
//        Matcher m = patternCompile.matcher(htmls);
//
//        //4.①利用Matcher中的group方法获取匹配的特定字符串 ②利用String的replace方法替换特定字符,得到抖音的去水印链接
//        String matchUrl ="";
//        while(m.find()) {
//            matchUrl = m.group(0).replaceAll("playwm", "play");
//        }
//
//        //5.将链接封装成流
//        //注:由于抖音对请求头有限制,只能设置一个伪装手机浏览器请求头才可实现去水印下载
//        Map<String, String> headers = new HashMap<>();
//        headers.put("Connection", "keep-alive");
//        headers.put("Host", "aweme.snssdk.com");
//        headers.put("User-Agent", "Mozilla/5.0 (iPhone; CPU iPhone OS 12_1_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/16D57 Version/12.0 Safari/604.1");
//
//        //6.利用Joup获取视频对象,并作封装成一个输入流对象
//        BufferedInputStream inStream = Jsoup.connect(matchUrl).headers(headers).timeout(10000).ignoreContentType(true).execute().bodyStream();
//
//        Date now = new Date();
//
//
//
//        String   filename = now.getTime()+".mp4";
//
//        response.reset();
//        //设置response
//         response.setContentType("video/mpeg4");
//        response.setHeader("content-disposition", "attachment; filename="+VideoHelper.buidFileName(userAgent,filename));
//
//
////        ServletOutputStream outputStream = response.getOutputStream();
////        byte[] buffer = new byte[inStream.available()];
////        int byteread = 0;
////        while ((byteread = inStream.read(buffer)) != -1) {
////            outputStream.write(buffer, 0, byteread);
////        }
////        outputStream.write(toByteArray(inStream));
//
////        byte[] buffer = new byte[inStream.available()];
////        inStream.read(buffer);
//        OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
//        int i = -1;
//        while ((i = inStream.read()) != -1) {
//            toClient.write(i);
//        }
//        inStream.close();
//
////        OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
////        toClient.write(buffer);
//        toClient.flush();
//        toClient.close();
//
//
//
//
//    }

    public static byte[] toByteArray(InputStream in) throws IOException {

        ByteArrayOutputStream out=new ByteArrayOutputStream();
        byte[] buffer=new byte[1024*4];
        int n=0;
        while ( (n=in.read(buffer)) !=-1) {
            out.write(buffer,0,n);
        }
        return out.toByteArray();
    }

    /**
     * 网络文件转换为byte二进制
     * @Title: toByteArray
     * @Description: TODO(这里用一句话描述这个方法的作用)
     * @param @param url
     * @param @return
     * @param @throws IOException    设定文件
     * @return byte[]    返回类型
     * @throws
     */
    public static byte[] toByteArray(String urlStr) throws IOException {
        URL url = new URL(urlStr);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        DataInputStream in = new DataInputStream(conn.getInputStream());
        ByteArrayOutputStream out=new ByteArrayOutputStream();
        byte[] buffer=new byte[1024*4];
        int n=0;
        while ( (n=in.read(buffer)) !=-1) {
            out.write(buffer,0,n);
        }
        return out.toByteArray();
    }

    /**
     * @throws IOException
     * @throws UnknownHostException
     * 网络文件转换为本地文件
     * @Title: toByteArray
     * @Description: TODO(这里用一句话描述这个方法的作用)
     * @param @param url
     * @param @return
     * @param @throws IOException    设定文件
     * @return byte[]    返回类型
     * @throws
     */
    public static void toBDFile(String urlStr, String bdUrl) throws IOException, UnknownHostException {
        URL url = new URL(urlStr);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        DataInputStream in = new DataInputStream(conn.getInputStream());
        byte[] data=toByteArray(in);
        in.close();
        FileOutputStream out=new FileOutputStream(bdUrl);
        out.write(data);
        out.close();
    }

    /**
     * 直接获取网络文件的md5值
     * @param urlStr
     * @return
     */
    public static String getMd5ByUrl(String urlStr){
        String md5 = null;
        try {
            URL url = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            DataInputStream in = new DataInputStream(conn.getInputStream());
            md5 = DigestUtils.md5Hex(in);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return md5;
    }

    /**
     * 获取网络文件的输入流
     * @param urlStr
     * @return
     */
    public static InputStream getInputStreamByUrl(String urlStr){
        DataInputStream in = null;
        try {
            URL url = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            in = new DataInputStream(conn.getInputStream());
        } catch (IOException e) {
            logger.error("url转换输入流失败,错误信息{}",e.getMessage());
        }
        return in;
    }





}
